# Load necessary libraries
library(tidyverse)
library(fixest)
library(xtable)
library(texreg)
library(stargazer)



# Load 1983 data ----

longer_83 <- readRDS("data/survey_1983_bjps.rds")
wave_3 <- readRDS("data/wave3_1983_bjps.rds")


# -----------------------
# Figure E.9 CDU/CSU voter’s disapproval of Greens in parliament
# -----------------------
# estimate
bad_grn_parl <- lm(like_greens_in_parlmnt ~ cdu_voter + sex_of_respondent + age_of_respondent + occupational_group+
                     religion, data = longer_83) %>% 
  broom::tidy() %>% 
  select(term,std.error, estimate) %>% 
  filter(term == "cdu_voter") %>% 
  mutate(  conf.low90 = estimate - qnorm(0.95)*std.error,
           conf.high90 = estimate + qnorm(0.95)*std.error,
           conf.low95 = estimate - qnorm(0.975) * std.error,
           conf.high95 = estimate + qnorm(0.975) * std.error) %>% 
  rename(treatment = term)

# plot
pd <- position_dodge(1)
ggplot(bad_grn_parl, aes(treatment, estimate)) +
  geom_hline(yintercept = 0, linetype = 'dotted') +
  geom_errorbar(aes(ymin = conf.low90, ymax = conf.high90),
                position = pd,
                width = 0, size = 1) +
  geom_errorbar(aes(ymin = conf.low95, ymax = conf.high95),
                position = pd,
                width = 0, size = 0.5) +
  geom_point(
    position = pd,
    size =2,
    shape = 21,
    fill  ='white') +
  theme_hanno()+
  xlab('') +ylab('Effect of being a CDU/CSU voter on opinion on Greens in Parliament') +
  coord_flip()  +
  scale_x_discrete(labels = c('CDU/CSU voter'))+ 
  ylim(c(-.4, .07))+
  theme(text = element_text(size=8))

ggsave('output/figures/figure_e_9_grn_in_parl_cdu_voters.png',
       width = 15, height = 4, units = "cm",
       dpi = 600)


# -----------------------
# Table E.12: CDU/CSU voter’s disapproval of Greens in parliament (same model as Fig E.9)
# -----------------------
# re-estimate
table_grn_parl <- lm(like_greens_in_parlmnt ~ cdu_voter + sex_of_respondent + age_of_respondent + occupational_group+
                       religion, data = longer_83)

stargazer(table_grn_parl,
                     label = "grn_in_parl_cdu_voters",
                     caption = "Disapproval of Green Party Entry among CDU/CSU voters",
                     covariate.labels = c("CDU Voter", "Sex", "Age", "Occupational Group", "Religion"), 
                     dep.var.labels=c('Evaluation of Greens'),
                     df = FALSE, 
                     omit.stat = c("rsq", "f", "ser"),
          out = "output/tables/appendix_table_e12.tex"
)











# -----------------------
# Figure E.10 Effect of Green's entrance into parliament on the CDU/CSU's voter evaluations of the party.
# -----------------------

cdu_dslike_grn <- feols(think_of_greens ~pre_post +i(pre_post, cdu_voter, 0) + employment_status + age_of_respondent|
                          respondent_number + wave,
                        data = longer_83) %>%
  broom::tidy() %>%
  select(term,std.error, estimate) %>%
  filter(term == "pre_post::1:cdu_voter") %>%
  mutate(  conf.low90 = estimate - qnorm(0.95)*std.error,
           conf.high90 = estimate + qnorm(0.95)*std.error,
           conf.low95 = estimate - qnorm(0.975) * std.error,
           conf.high95 = estimate + qnorm(0.975) * std.error) %>%
  rename(treatment = term)



## Plot

ggplot(cdu_dslike_grn, aes(treatment, estimate)) +
  geom_hline(yintercept = 0, linetype = 'dotted') +
  geom_errorbar(aes(ymin = conf.low90, ymax = conf.high90),
                position = pd,
                width = 0, size = 1) +
  geom_errorbar(aes(ymin = conf.low95, ymax = conf.high95),
                position = pd,
                width = 0, size = 0.5) +
  geom_point(
    position = pd,
    size =2,
    shape = 21,
    fill  ='white') +
  theme_hanno() +
  xlab('') +ylab('Effect of Green parliament entrance on opinion of the Greens, for CDU/CSU voters') +
  coord_flip()  +
  scale_x_discrete(labels = c('Post-election, CDU/CSU voter'))+ 
  ylim(c(-1.3, .7))+
  theme(text = element_text(size=8))

ggsave('output/figures/figure_e_10_post_cdu_liking.png',
       width = 15, height = 4, units = "cm",
       dpi = 600)


# -----------------------
# Table E.11:  Effect of Green Party Parliament entry on CDU/CSU voters approval of the party (same model as Fig E10)
# -----------------------
#re-estimating
table_dslike_grn <- feols(think_of_greens ~pre_post +i(pre_post, cdu_voter, 0) + employment_status + age_of_respondent|
                             respondent_number + wave,
                           data = longer_83)
# Setting a dictionary
setFixest_dict(c('think_of_greens' = "Opinion of Green Party (-5 - +5)",
                 respondent_number = "Respondent",
                 wave = "Survey Wave"))



etable(table_dslike_grn,
       se = "cluster",
       dict = c("cdu_voter $\times$ pre_post $=$ 1" = "Post election \\\\nx CDU/CSU voter"),
       tex = TRUE,
       title = "Effect of Green Party Parliament entry on CDU/CSU voters approval of the party",
       fitstat = ~n + r2 + ar2 + wr2,
       digits = 3,
       label = "table:post_cdu_liking",
       drop = c("employment_status", "age_of_respondent"),
       extralines = c("Covariates", "Yes"),
       file = 'output/tables/appendix_table_e11.tex'
)










# -----------------------
# Figure E11 The association between mentioning dislike of the Greens' policy and behaviour and voting for the CDU/CSU in 1983.
# -----------------------

#do plot now
reasons_dislike <- lm(cdu_voter_83~behaviour_grn_dislike_any+ policy_grn_dislike_any + age_of_respondent + occupational_group+
                         religion, data = wave_3) %>%
  broom::tidy() %>%
  select(term,std.error, estimate) %>%
  filter(term %in% c("behaviour_grn_dislike_any", "policy_grn_dislike_any")) %>%
  mutate(  conf.low90 = estimate - qnorm(0.95)*std.error,
           conf.high90 = estimate + qnorm(0.95)*std.error,
           conf.low95 = estimate - qnorm(0.975) * std.error,
           conf.high95 = estimate + qnorm(0.975) * std.error) %>%
  rename(treatment = term)
## Plot

ggplot(reasons_dislike, aes(treatment, estimate)) +
  geom_hline(yintercept = 0, linetype = 'dotted') +
  geom_errorbar(aes(ymin = conf.low90, ymax = conf.high90),
                position = pd,
                width = 0, size = 1) +
  geom_errorbar(aes(ymin = conf.low95, ymax = conf.high95),
                position = pd,
                width = 0, size = 0.5) +
  geom_point(
    position = pd,
    size =2,
    shape = 21,
    fill  ='white') +
  theme_hanno()+
  xlab('') +ylab('Voted CDU/CSU in 1983 (0-1)') +
  coord_flip()  +
  scale_x_discrete(labels = c("Greens' behaviour mentioned",
                              "Greens' policy mentioned"))+
  theme(text = element_text(size=8))


ggsave('output/figures/figure_e_11_reasons_dislike_Grn.png',
       width = 15, height = 7, units = "cm",
       dpi = 600)



# -----------------------
# Table E.9: Motivation to dislike the Greens and CDU/CSU voting in 1983 (same model as Fig E11)
# -----------------------
#re-estimate
table_reasons <- lm(cdu_voter_83~behaviour_grn_dislike_any+ policy_grn_dislike_any + age_of_respondent + occupational_group+
                        religion, data = wave_3)

stargazer(table_reasons,
                     covariate.labels = c("Behaviour Mentioned", "Policy Mentioned"),
                     omit = c("sex_of_respondent", "age_of_respondent", "occupational_group", "religion"), 
                     dep.var.labels=c('Voted CDU/CSU in 1983 (0-1)'),
                     df = FALSE, 
                     label = "table_reasons",
                     omit.stat = c("rsq", "f", "ser"),
                     add.lines = list(c("Covariates:", "Gender, Age, Occupational Group, Religion")),
                     out = "output/tables/appendix_table_e9.tex")


# -----------------------
# Table E.10: Motive to dislike the Greens and CDU/CSU voting conditional on Green party representation in state parliament
# -----------------------
control <- lm(cdu_voter_83~behaviour_grn_dislike_any+ policy_grn_dislike_any +
                age_of_respondent + occupational_group+
                religion, data = wave_3[wave_3$greens_land_parl == 0,])
treated <- lm(cdu_voter_83~behaviour_grn_dislike_any+ policy_grn_dislike_any +
                age_of_respondent + occupational_group+
                religion, data = wave_3[wave_3$greens_land_parl == 1,])

stargazer(control, treated,
                     covariate.labels = c("Behaviour Mentioned", "Policy Mentioned"),
                     omit = c("sex_of_respondent", "age_of_respondent", "occupational_group", "religion"), 
                     dep.var.labels=c('Voted CDU/CSU in 1983 (0-1)'),
                     df = FALSE, 
                     omit.stat = c("rsq", "f", "ser"),
                     add.lines = list(c("Covariates:", "Gender, Age, Occupational Group, Religion"),
                                      c("Sample", "Greens Not in State Parliament", "Greens in State Parliament")),
          out = "output/tables/appendix_table_e10.tex")





# -----------------------
# Table E.13: Approval of Green Party by State among CDU/CSU voters
# -----------------------

# Compute summary statistics for first pre-election wave
wave_1 <- longer_83 %>%
  filter(wave == 1) %>% 
  rename(state = `state_-_bundesland`)

averages_w1 <- wave_1 %>%
  filter(cdu_voter == 1) %>% 
  group_by(state) %>%
  summarise(
    `Avg. Approval (1-11)` = round(mean(think_of_greens, na.rm = T), 2),
    SE = round(sd(think_of_greens, na.rm = T) / sqrt(n()), 2),
    N = n()
  )

# Create LaTeX table
stargazer(averages_w1,
          summary = FALSE,
                      label= "table:grn_approval_by_state", 
                      caption = "Approval of Green Party by State among CDU/CSU voters",
       out = "output/tables/appendix_table_e13.tex"
)

